import 'package:flutter/material.dart';
import 'package:flutter_09_game/generated/locales.g.dart';
import 'package:flutter_09_game/widgets/appbar/common_app_bar.dart';
import 'package:get/get.dart';

import 'package:flutter_09_game/utils/log/utils_log.dart';
import 'package:flutter_09_game/config/app_color.dart';
import 'package:flutter_09_game/widgets/empty/empty_no_data.dart';

import 'package:flutter_inappwebview/flutter_inappwebview.dart';

import 'package:flutter_09_game/base/widget/base_get_builder.dart';

import 'web_service_logic.dart';

class WebServicePage extends StatelessWidget {
  WebServicePage({super.key});

  final WebServiceLogic logic = Get.put(WebServiceLogic());

  @override
  Widget build(BuildContext context) {
    return BaseGetBuilder<WebServiceLogic>(

      appBar: CommonAppBar(title: LocaleKeys.customerServiceCenter.tr),
      builder: (c) {
        return Stack(
          children: [
            Positioned.fill(child: _buildWebView()),
            // 顶部进度条
            Positioned(
              top: 0,
              left: 0,
              right: 0,
              child: _buildProgressBar(),
            ),
          ],
        );
      },
    );
  }

  /// 构建顶部进度条
  Widget _buildProgressBar() {
    return Obx(() {
      // 只在加载时显示进度条
      if (!logic.isWebLoading.value || logic.loadingProgress.value >= 1.0) {
        return const SizedBox.shrink();
      }

      return SizedBox(
        height: 4,
        child: LinearProgressIndicator(
          value: logic.loadingProgress.value,
          backgroundColor: AppColor.gameBorderColor,
          valueColor: const AlwaysStoppedAnimation<Color>(AppColor.primary),
        ),
      );
    });
  }

  /// 构建WebView
  Widget _buildWebView() {
    return Obx(() {
      if (logic.hasError.value) {
        return EmptyNoData.notYetView();
      }

      return InAppWebView(
        initialUrlRequest: URLRequest(url: WebUri(logic.url.value)),
        initialSettings: InAppWebViewSettings(
          userAgent: 'game_turntable_web',
          useShouldOverrideUrlLoading: true,
          mediaPlaybackRequiresUserGesture: false,
          allowsInlineMediaPlayback: true,
          javaScriptEnabled: true,
          domStorageEnabled: true,
          databaseEnabled: true,
          clearCache: false,
          cacheEnabled: true,
          supportZoom: true,
          builtInZoomControls: false,
          displayZoomControls: false,
          useHybridComposition: true,
        ),
        onWebViewCreated: (InAppWebViewController webViewController) {
          logic.webViewController = webViewController;
          // 注册JavaScript处理器
          logic.registerJavaScriptHandlers();
        },
        onConsoleMessage: (webViewController, ConsoleMessage message) {
          // message.message

          clog('onConsoleMessage   ${message.message}');
          // controller.consoleMessages.add(message.message);
        },
        onLoadStart: (InAppWebViewController webViewController, WebUri? url) {
          logic.onLoadStart(webViewController, url);
        },
        onLoadStop: (InAppWebViewController webViewController, WebUri? url) {
          logic.onLoadStop(webViewController, url);
        },
        onProgressChanged:
            (InAppWebViewController webViewController, int progress) {
          logic.onProgressChanged(webViewController, progress);
        },
        onLoadError: (InAppWebViewController webViewController, Uri? url,
            int code, String message) {
          logic.onLoadError(webViewController,
              url != null ? WebUri.uri(url) : null, code, message);
        },
        onLoadHttpError: (InAppWebViewController webViewController, Uri? url,
            int statusCode, String description) {
          logic.onLoadHttpError(webViewController,
              url != null ? WebUri.uri(url) : null, statusCode, description);
        },
        shouldOverrideUrlLoading: (controller, navigationAction) async {
          return NavigationActionPolicy.ALLOW;
        },
      );
    });
  }
}
